package com.intermancer.predictor.data;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.intermancer.predictor.system.InitializationException;

public class BaseFileDAO<T> {
	
	protected Class<T> clazz;
	protected String homeDirectory;

	public Object getObject(String filename) {
		Object retreivedObject = null;
		Resource resource = null;
		File file = null;
		FileReader fileReader = null;
		
		try {
			resource = new FileSystemResource(filename);
			file = resource.getFile();
			fileReader = new FileReader(file);
			retreivedObject = Unmarshaller.unmarshal(clazz, fileReader);
		} catch (Exception e) {
			throw new InitializationException(e);
		} finally {
			if (fileReader != null) {
				try {
					fileReader.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		
		return retreivedObject;
	}

	public void putObject(String filename, Object object) {
		Resource resource = null;
		File file = null;
		FileWriter fileWriter = null;
		
		try {
			resource = new FileSystemResource(filename);
			file = resource.getFile();
			fileWriter = new FileWriter(file);
			Marshaller.marshal(object, fileWriter);
		} catch (Exception e) {
			throw new InitializationException(e);
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	public void deleteFile(String filename) {
		Resource resource = null;
		File file = null;
	
		try {
			resource = new FileSystemResource(filename);
			file = resource.getFile();
			file.delete();
		} catch (Exception e) {
			throw new InitializationException(e);
		}
	}

	public String getHomeDirectory() {
		return homeDirectory;
	}

	public void setHomeDirectory(String homeDirectory) {
		this.homeDirectory = homeDirectory;
	}

}
